# 多元·线性回归
import numpy as np  #as重命名
import matplotlib.pyplot as plt
import pandas as pd
import LinearRegression
import math
# 1.读取数据，形成矩阵x,y
data = pd.read_excel('WaterData.xlsx')
data = (data.to_numpy()).T
x = (data[0:7, :])
z = data[7, :]
z = z.reshape(-1,1)
# 2.1调用线性回归函数（使用解析解方式计算）
a = LinearRegression.linear_regression(x, z)



# 2.2调用线性回归函数（使用梯度下降法计算）   
# ########有问题，暂时不要用 
# alpha = 0.001
# # alpha = np.array([[alpha]])
# max_iter=10000
# tol = 1e-4
# x_rows,x_cols = x.shape
# # x = np.hstack((np.ones(x_rows).reshape(x_rows,1),x))
# x_T = x.T
# z_T = z.T
# # a的初始值
# # # a = np.array([[120,1]])
# a = np.array([[0.001552507,-0.044120565,3.95317E-05,0.005108583,-4.71338E-05,0.049618433,-0.00416312]])
# a = a.T
# diff = math.inf
# # # 定义迭代次数
# i = 0
# print(x_T.shape,alpha*x_T)
# while diff > tol :
#     f_y_pre = z_T@z - 2*z_T@x@a + a.T@x_T@x@a
#     a = a - alpha*x_T@(-z+x@a)
#     f_y = z_T@z - 2*z_T@x@a + a.T@x_T@x@a
#     diff = np.linalg.norm(f_y - f_y_pre)
#     i = i+1
#     if i > max_iter:
#         print("迭代次数：",i) 
#         break
# print("迭代次数：",i) 


# 2.3输出结果
print("a: \n",a.shape,a)
y_delta = np.dot(x, a)
print("y_delta: \n",y_delta)
# #3.画图
x_lable = np.array([1,2,3,4,5,6,7])
plt.figure()
plt.scatter(x_lable,z)
plt.plot(x, y_delta,marker='o',linestyle='--',color='r', label='Fitted Line')
plt.title('Simple Scatter Plot')
plt.xlabel('X Axis')
plt.ylabel('Y Axis')
plt.grid()
plt.show()